const http = require('http')
const url = require('url')
const fs = require("fs")
const path = require("path")
const { getWeather ,getWeatherByUrl,getCityInfoByLike} = require("./weather")


http.createServer(function (request, response) {
    let query = url.parse(request.url, true).query
    let pathname = url.parse(request.url, true).pathname
    response.writeHead(200, { 'Content-Type': 'application/json' })
    if (pathname == "/api/weather") {
        let city = query.city
        getWeather(city).then(data => {
            response.end(JSON.stringify(data))
        }).catch(err=>{
            console.log(err)
            response.end(JSON.stringify({code:0,err}))
        })
    }
    if (pathname == "/api/cities/ch") {
        const chinacity = fs.readFileSync(path.join(__dirname, "data/city.json"))
        const chinacityJson = JSON.parse(chinacity.toString())
        response.end(JSON.stringify(Object.keys(chinacityJson)))
    }
    if (pathname == "/api/cities/out") {
        const internationalCity = fs.readFileSync(path.join(__dirname, "data/internationalCity.json"))
        const internationalCityJson = JSON.parse(internationalCity.toString())
        response.end(JSON.stringify(Object.keys(internationalCityJson)))
    }

    if (pathname == "/api/v2/getCityInfoByLike") {
        let keyword = query.keyword
        getCityInfoByLike(keyword).then(data=>{
            response.end(JSON.stringify(data))
        }).catch(err=>{
            console.log(err)
            response.end(JSON.stringify({code:0,err}))
        })
    }

    if (pathname == "/api/v2/weather") {
        let apiPath = query.apiPath
        getWeatherByUrl(apiPath).then(data=>{
            response.end(JSON.stringify(data))
        }).catch(err=>{
            console.log(err)
            response.end(JSON.stringify({code:0,err}))
        })
    }

}).listen(8080);

console.log('服务启动： http://127.0.0.1:8080/')
console.log([
	'/api/weather?city=?',
	'/api/cities/ch',
	'/api/cities/out',
    '/api/v2/getCityInfoByLike?keyword=?',
    '/api/v2/weather?apiPath=?'
])